package cn.le.utils;

import cn.le.crawler.ipproxy.IpProxyData;
import cn.le.crawler.ipproxy.IpXiCiDailiData;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.persistence.Id;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class IpProxyPool {

    private static final List<Proxy> IP_POOL = new CopyOnWriteArrayList<>();

    private static final List<Proxy> IP_RETAIN  = new CopyOnWriteArrayList<>();

    public static void replacePool(List<IpProxyData> list){
        IP_POOL.clear();
        list.forEach(data->{
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(data.getIp(), data.getPort()));
            IP_POOL.add(proxy);
        });
    }

    public static Proxy getProxy(){
        if (!CollectionUtils.isEmpty(IP_POOL)){
            return IP_POOL.get(0);
        }
        if (!CollectionUtils.isEmpty(IP_RETAIN)){
            return IP_RETAIN.get(0);
        }
        Assert.isTrue(true,"代理池为空");
        return IP_POOL.get(0);
    }

    public static void retain(Proxy proxy){
        IP_RETAIN.add(proxy);
    }

    public static void remove(Proxy proxy){
        IP_POOL.remove(proxy);
    }

}
